<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="负责人" prop="leaderName">
        <el-input
          v-model="queryParams.leaderName"
          placeholder="请输入负责人名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:item:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:item:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:item:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          :loading="exportLoading"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['base:item:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange" @row-click="rowClick">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="项目名称" align="center" prop="name"/>
      <el-table-column label="负责人名称" align="center" prop="leaderName"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:item:edit']"
            @click.stop.prevent
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="addBb(scope.row)"
            v-hasPermi="['base:item:baobiao']"
            @click.stop.prevent
          >添加报表
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="addZl(scope.row)"
            v-hasPermi="['base:item:export']"
            @click.stop.prevent
          >添加资料员
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:item:remove']"
            @click.stop.prevent
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-drawer
      title="项目资料员"
      :visible.sync="showTable"
      direction="rtl"
      size="60%">
      <el-row :gutter="20" class="mb8">
        <el-col :span="1.5">
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col>
          <el-table v-loading="loading" :data="categoryPersonConfigList">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="资料员" align="center" prop="leaderName"/>
            <el-table-column label="楼号" align="center" prop="buildingName"/>
            <el-table-column label="类目" align="center" prop="categoryName"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="editZly(scope.row)"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="zlyDelete(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-drawer>


    <!-- 添加或修改项目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="name" v-if="form.id==null">
          <el-input v-model="form.name" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="项目名称" v-else>
          <el-input v-model="form.name" readonly placeholder="请输入项目名称"/>
        </el-form-item>

        <el-form-item label="类目" prop="categoryIdList" v-if="form.id!=null">
          <el-cascader v-model="form.categoryIdList" :options="categoryOptions" :props="categoryps"
                       :style="{width: '100%'}" :show-all-levels="false" placeholder="请选择类目" filterable clearable>
          </el-cascader>
        </el-form-item>


        <el-form-item label="楼号" v-if="form.id!=null">
          <el-select @change="addRow" placeholder="请选择楼号" style="width:380px;">
            <el-option v-for="(item, index) in buildingOptions" :key="index" :label="item.dictLabel"
                       :value="index"></el-option>
          </el-select>
        </el-form-item>

        <el-table
          :data="buildingListData"
          align="center"
          style="width: 100%" v-if="form.id!=null">
          <el-table-column
            prop="categoryName"
            label="楼号">
          </el-table-column>
          <el-table-column
            prop="area"
            label="面积">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.area" size="small" controls-position="right"
                               :min="0"></el-input-number>
            </template>
          </el-table-column>

          <el-table-column
            prop="orderNum"
            label="操作"
            width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteBuilding(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>


        <el-form-item label="项目负责人" prop="leaderCode" v-if="form.id==null">
          <el-select v-model="form.leaderCode" placeholder="请选择负责人" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in userOptions" :key="item.id" :label="item.nickName"
                       :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加资料员 -->
    <el-dialog :title="title" :visible.sync="zlOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="itemName" v-if="form.id==null">
          <el-input v-model="form.itemName" placeholder="请输入项目名称"/>
        </el-form-item>

        <el-form-item label="资料员" prop="leaderCode" v-if="form.id==null">
          <el-select v-model="form.leaderCode" placeholder="请选择资料员" clearable :style="{width: '100%'}">
            <el-option v-for="item in userOptions" :key="item.id" :label="item.nickName"
                       :value="item.userName"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="类目" prop="categoryIdList">
          <el-cascader v-model="form.categoryIdList" :options="categoryOptions" :props="categoryps"
                       :style="{width: '100%'}" :show-all-levels="false" placeholder="请选择类目" filterable clearable>
          </el-cascader>
        </el-form-item>

        <el-form-item label="楼号">
          <el-select v-model="buildingIdList" placeholder="请选择楼号" multiple clearable
                     :style="{width: '100%'}">
            <el-option v-for="(item, index) in buildingOptions" :key="index" :label="item.dictLabel"
                       :value="item.dictValue" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="zlySubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {listItem, getCateList, getItem, delItem, addItem, updateItem, exportItem} from "@/api/base/item";
import {selectProjectmanrList, selectZlyList} from "@/api/system/user";
import {
  listCategoryPersonConfig,
  getCategoryPersonConfig,
  delCategoryPersonConfig,
  addCategoryPersonConfig,
  updateCategoryPersonConfig
} from "@/api/base/categoryPersonConfig";


export default {
  name: "Item",
  data() {
    return {
      categoryPersonConfigList: [],
      zylList: [],
      buildingListData: [],
      buildingIdList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showTable: false,
      // 总条数
      total: 0,
      // 项目管理表格数据
      itemList: [],
      userOptions: [],
      categoryOptions: [],
      buildingOptions: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      zlOpen: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        categoryIdList: null,
        buildingIdList: null,
        leaderCode: null,
        leaderName: null,
        status: null,
        delFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        leaderCode: [{
          required: true,
          message: '请选择人员',
          trigger: 'blur'
        }],
        name: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ],
        categoryIdList:[
          {required: true, message: "分类不能为空", trigger: "blur"}
        ]
      },
      categoryps: {
        "multiple": true,
        "value": "id",
        "label": "name"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询项目管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    selectProjectmanrList() {
      selectProjectmanrList().then(response => {
        this.userOptions = response.rows
      });
    },
    selectZlyList() {
      selectZlyList().then(response => {
        this.userOptions = response.rows
      })
    },
    rowClick(row, column, event) {
      this.showTable = true;
      let obj = {}
      obj.itemId = row.id
      listCategoryPersonConfig(obj).then(Response => {
        this.categoryPersonConfigList = Response.rows
      })
      // this.getDetailListById(row.id);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.zlOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.userOptions = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.selectProjectmanrList()
      this.reset();
      this.open = true;
      this.title = "添加项目管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getItem(id).then(response => {
        console.log(response)
        this.form = response.data;
        this.buildingListData = response.data.buildingListData
        this.categoryOptions = this.handleTree(response.categoryOptions, "id", "pid");
        this.buildingOptions = response.buildingOptions;
        this.form.buildingIdList = response.buildIds
        this.form.categoryIdList = response.categoryIdList
        // this.form.categoryIdList = [[18, 20], [1, 5, 9]]
        this.open = true;

        this.title = "修改项目管理";
      });
    },
    editZly(row) {
      this.reset();
      const id = row.id
      getCategoryPersonConfig(id).then(response => {
        this.form = response.data;

        this.categoryOptions = this.handleTree(response.categoryOptions, "id", "pid");
        this.buildingOptions = response.buildingOptions;
        this.buildingIdList = response.buildingIdList
        this.form.categoryIdList = response.categoryIdList
        // this.buildingIdList = response.buildingIdList
        // this.form.categoryIdList = [[1,5,8],[1,5,9]]

        this.zlOpen = true;
        this.title = "编辑资料员";
      });
    },
    //添加经济运行分析
    addBb(row){
      this.$router.push("/report/addReport?itemId="+row.id);
    },
    /** 添加资料员 */
    addZl(row) {
      this.selectZlyList()
      this.reset();
      const id = row.id || this.ids
      getCateList(row).then(response => {
        this.form = response.data;

        this.categoryOptions = this.handleTree(response.categoryOptions, "id", "pid");
        this.buildingOptions = response.buildingOptions;
        this.buildingIdList = response.buildingIdList
        this.form.categoryIdList = response.categoryIdList
        // this.buildingIdList = response.buildingIdList
        // this.form.categoryIdList = [[1,5,8],[1,5,9]]

        this.zlOpen = true;
        this.title = "添加资料员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            let buildingListData = this.buildingListData
            if (null != buildingListData && 0 < buildingListData.length) {
              for (let i = 0; i < buildingListData.length; i++) {
                let bu = buildingListData[i]
                if (null == bu.area) {
                  this.$modal.msgError("[" + bu.categoryName + "]-未填写面积");
                  return
                }
              }
            }
            this.form.buildingListData = this.buildingListData
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.form = {}
              this.buildingListData = []
              this.open = false;
              this.getList();
            });
          } else {
            let form = this.form
            let userList = this.userOptions
            let user = userList[form.leaderCode]
            form.leaderCode = user.userName
            form.leaderName = user.nickName
            addItem(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 资料员提交按钮 */
    zlySubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.buildingIdList)
          if(1>this.buildingIdList.length){
            this.$modal.msgError("请选择楼号!");
            return false;
          }
          this.form.buildingIdList = this.buildingIdList
          if (this.form.id != null) {
            updateCategoryPersonConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.showTable = false;
              this.cancel()
            });
          } else {
            let form = this.form
            addCategoryPersonConfig(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.showTable = false;
              this.cancel()
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目管理编号为"' + ids + '"的数据项？').then(function () {
        return delItem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    zlyDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除项目管理编号为"' + ids + '"的数据项？').then(function () {
        return delCategoryPersonConfig(ids);
      }).then(() => {
        this.showTable = false;
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有项目管理数据项？').then(() => {
        this.exportLoading = true;
        return exportItem(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    addRow(index) {
      console.log(index)
      let buildingOptions = this.buildingOptions
      let building = buildingOptions[index]
      //1.先判断该工序是否已经选择
      let flag = this.buildingListData.some(f => f.categoryId == building.dictValue);
      if (flag) {
        console.log(this)
        this.$modal.msgError("该楼号已添加请重新选择!");
        return false;
      }
      let obj = {}
      obj.itemId = this.form.id
      obj.categoryId = building.dictValue
      obj.categoryName = building.dictLabel
      this.buildingListData.push(obj);
      // this.addProcessList(id,"0")
    },
    handleDeleteBuilding(row) {
      this.buildingListData.splice(this.buildingListData.findIndex(item => item.categoryId == row.dictValue), 1)
    }
  }
};
</script>
